//============================hash前端路由
/*
* 夕空 flashme.cn 2020-4-19
//初始化
window.Router = new Router();
window.Router.init();
//方法
Router.route("/url", function, function);
Router.route(url地址, 触发函数, 退出函数);
1.填写"hash"将会监听每次地址变更的触发
2.添加地址层级关系
  例：Router.routes['/home'].subset=['/sub1','/sub2']
  /home的子地址有/sub1、/sub2，打开子集地址/home将不执行退出函数
*/
function Router() {
    this.routes = {};
    this.currentUrl = '';
    this.beforeUrl = '';
}
Router.prototype.route = function (path, callback, removeback) {
    var obj = { start: false, subset: [] };
    obj.callback = callback || function () { };
    if (removeback) obj.leave = removeback;
    this.routes[path] = obj;
};
Router.prototype.refresh = function (ev) {
    this.routes["hash"] && this.routes["hash"].callback();

    this.currentUrl = location.hash.slice(1).split("?")[0] || '/';
    if (this.routes[this.currentUrl] && this.routes[this.currentUrl].start == false) {
        this.routes[this.currentUrl].callback();
        this.routes[this.currentUrl].start = true;
        this.routes[this.currentUrl].before = this.beforeUrl;//记录上一个地址
    }
    //将之前的地址判断是否执行退出
    this.parentUrl(this.beforeUrl);

    //判断全部地址是否执行退出
    for (var k in this.routes) {
        var than = this.routes[k];
        if (than.start && this.currentUrl != k) {
            //处在打开状态 & 当前地址不等于此地址
            if (!this.forsub(than)) {
                than.start = false;
                than.leave && than.leave();
            }

        }
    }
    this.beforeUrl = this.currentUrl;

};
Router.prototype.forsub = function (than) {
    //for 子地址非打开状态  >> 执行退出函数
    for (var i in than.subset) {//判断子集是否打开状态
        if (this.routes[than.subset[i]] && this.routes[than.subset[i]].start) {
            return true;
        }
    }
    return false;
}
Router.prototype.parentUrl = function (before) {
    if (before && this.currentUrl != before && this.routes[before] && this.routes[before].start && !this.forsub(this.routes[before])) {
        this.routes[before].start = false;
        this.routes[before].leave && this.routes[before].leave();
        var parent = this.routes[before].before;
        if (parent) {
            this.routes[before].before = null;
            this.parentUrl(parent);
        }
    }

}
Router.prototype.init = function () {
    window.addEventListener('load', this.refresh.bind(this), false);
    window.addEventListener('hashchange', this.refresh.bind(this), false);
}


//解析地址栏参数 new getUrlSearch()
//new getUrlSearch(true) 将会解析#后面参数
function getUrlSearch(hash) {
    var name, value;
    var str = location.href.split("#");
    str = (hash && str.length>1) ? str[1] : str[0];
    str = str.substring(str.indexOf("?") + 1);
    var arr = str.split("&");
    for (var i = 0; i < arr.length; i++) {
        var num = arr[i].indexOf("=");
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = decodeURI(arr[i].substring(num + 1));
            this[name] = value;
        }
    }
}
//Object转地址栏参数
function obj2Param(obj) {
    return Object.keys(obj).map(key => {
        return key + '=' + obj[key]
    }).join('&')
}


// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(D)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(Y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("YYYY-MM-DD hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("YYYY-M-D h:m:s.S")      ==> 2006-7-2 8:9:4.18
// (new Date("2023-5-23")).Format("YYYY-MM-DD hh:mm:ss")
Date.prototype.Format = function (fmt, newtime) {
    var thistime = this;
    //兼容设置
    if (!thistime.getFullYear() && newtime) {
        thistime = new Date(getFormatTime(newtime))
    }

    var o = {
        "M+": thistime.getMonth() + 1, //月
        "D+": thistime.getDate(), //日
        "h+": thistime.getHours(), //时
        "m+": thistime.getMinutes(), //分
        "s+": thistime.getSeconds(), //秒
        "q+": Math.floor((thistime.getMonth() + 3) / 3), //季度
        "S": thistime.getMilliseconds() //毫秒
    };
    if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (thistime.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


// 按时间当天与当年呈现时间
function resetnow(_time) {
    var now = new Date();
    var time = new Date(_time);
    if (!time.getFullYear()) {
        time = new Date(getFormatTime(_time))
    }
    if (time.getFullYear() == now.getFullYear()) {
        var today = new Date();
        today.setHours(0, 0, 0, 0);
        today = today.getTime();
        var h = 1000 * 60 * 60, s = now.getTime() - time.getTime();
        if(s < h){
            var m = parseInt(s / 60000);
            return m>0?m+"分钟前":"刚刚";
        }else if (today < time.getTime()) {
            return '今天 ' + time.Format("hh:mm:ss", _time);
        } else if (today-time.getTime() < h*24) {
            return '昨天 ' + time.Format("hh:mm:ss", _time);
        }
        return time.Format("MM/DD hh:mm", _time);
    }
    return time.Format("YYYY/MM/DD", _time);
}


//日期兼容设置 针对格式 2020-12-1 14:49:00 +00:00
function getFormatTime(newtime) {
    if(newtime>0){
        return newtime;
    }
    var parse = Date.parse(newtime);
    if(parse){
        return parse;
    }
    var fmtArr = String(newtime).split(' ');
    var rq = fmtArr[0].replace(/-/g, "/");
    var sj = String(fmtArr[1]).split('.')[0];
    var hm = Number(String(fmtArr[1]).split('.')[1]);
    //var sq = fmtArr[2] ? String(fmtArr[2]).match(/[^\+|^\-]+(?=\:)/) : 0;
    //sq = sq ? (Number(sq[0]) * 60 * 60 * 1000) : 0;
    //计算时区差额
    var sq = fmtArr[2] ? (new Date(rq + ' ' + fmtArr[2].substr(1))).getTime() - (new Date(rq)).getTime() : 0;
    var _time = (new Date(rq + ' ' + sj)).getTime() + hm;
    var zz = (new Date()).getTimezoneOffset() * 60 * 1000;
    return (fmtArr[2] && String(fmtArr[2]).substr(0, 1) == '+') ? _time - sq - zz : _time + sq - zz;
}


function ppwrap(text) {
    //将回车符换成p标签
    return text != "" && text != null ? '<p>' + text.replace(/\r/g, '').replace(/\n*$/g, '').replace(/\n/g, '</p><p>') + '</p>' : "";
}

function base64ToBlob(urlData) {
    var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1].replace(/\s|\n/g, "")), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}




export {
	Router,base64ToBlob,resetnow,getUrlSearch,obj2Param
};